package br.com.passeionaweb.appengine.tabelafipe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.passeionaweb.appengine.tabelafipe.data.DataProvider;
import br.com.passeionaweb.appengine.tabelafipe.data.Make;
import br.com.passeionaweb.appengine.tabelafipe.data.Model;
import br.com.passeionaweb.appengine.tabelafipe.data.PMF;
import br.com.passeionaweb.appengine.tabelafipe.data.Version;
import br.com.passeionaweb.appengine.tabelafipe.data.Year;
import br.com.passeionaweb.appengine.tabelafipe.data.YearVersion;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class UpdateYearVersionServlet extends HttpServlet {

	private static final PersistenceManager pm = PMF.get().getPersistenceManager();
	private static final Logger LOG = Logger.getLogger(UpdateVersionsServlet.class.getName());
	private static int laststop = 0;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
			IOException {
		long start = Calendar.getInstance().getTimeInMillis();
		boolean result = updateYearVersion();
		long end = Calendar.getInstance().getTimeInMillis();
		resp.getWriter().write("{result:"+result+",time:"+((end - start) / 1000)+"}");

	}

	@SuppressWarnings("unchecked")
	private boolean updateYearVersion() {
		try {
			List<Version> versions = (List<Version>) pm.newQuery(Version.class).execute();
			int total = versions.size();
			for (int n = 0; n < versions.size(); n++) {
				logPercentage(laststop, total);
				if (n < laststop && laststop < total) {
					break;
				} else if (laststop >= total) {
					laststop = n - 1;
				}
				Version version = versions.get(n);
				Model model = pm.getObjectById(Model.class, version.getModelid());
				Make make = pm.getObjectById(Make.class, model.getMakeid());
				JSONArray yearsjson = new JSONArray(DataProvider.getYearsJSON(make, model));
				for(int j =0; j<yearsjson.length();j++){
					Year year = Year.getYear(yearsjson.getJSONObject(j).getString(Year.KEY_YEAR));
						List<YearVersion> yearversions = new ArrayList<YearVersion>();
						try{
						JSONArray versionarray = new JSONArray(DataProvider.getVersionsJSON(make, model, year));
						for (int i = 0; i < versionarray.length(); i++) {
							JSONObject versionJson = versionarray.getJSONObject(i);
							Version ver =  Version.getVersion(versionJson.getString(Version.KEY_VERSION));
							if(!YearVersion.exists(year,ver)){
								yearversions.add(new YearVersion(year.getId(), ver.getId()));
							}
						}
						}finally{
							pm.makePersistentAll(yearversions);
						}
				}
				laststop++;
			}
			
			return true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			LOG.log(Level.SEVERE,"Error updating YEARVERSIONS",e);
			e.printStackTrace();
			return false;
		}
	}

	private void logPercentage(int done, int size) {
		Float percentage = Float.valueOf(done) / Float.valueOf(size) * 100;
		LOG.info("Updating YEARVERSIONS: " + percentage+ "% ("+ done+"/"+size+")");
	}
}
